package com.yand.thinkingInJava.thinkingInJava21.ShareResource;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;


/**
 *
 * lock 获取锁，比较倔强 获取不到就一直等一直等
 *
 * tryLock 尝试获取锁，获取不到就换人，要不获取一段时间 ，这段时间内等... 结束 换
 *
 */
public class AttemptLocking {

    private ReentrantLock lock = new ReentrantLock();

    public void untimed(){
        boolean captured = lock.tryLock();
        try{
            System.out.println("tryLock(): "+captured);
        }finally {
            if(captured){
                lock.unlock();
            }
        }
    }

    public void timed(){
        boolean captured = false;
        try{
            captured =  lock.tryLock(2,TimeUnit.SECONDS);
        }catch (InterruptedException e){
            throw new RuntimeException(e);
        }

        try{
            System.out.println("tryLock(2,TimeUnit.SECONDS):"+captured);
        }finally {
            if(captured){
                lock.unlock();
            }
        }
    }



    public static void main(String [] args){

        final AttemptLocking al = new AttemptLocking();

        al.untimed();
        al.timed();

        new Thread(){
            {setDaemon(true);}

            public void run(){
                al.lock.lock();
                System.out.println("acquired");
            }
        }.start();
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        Thread.yield();
        al.untimed();
        al.timed();




    }























}
